﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Common.Controls;
using Common.Data;
using Common.Entities;
using Common.Packets;
using Lidgren.Network;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using ShootLife2D.GUI.Controls;
using TomShane.Neoforce.Controls;
using Console = TomShane.Neoforce.Controls.Console;

namespace ShootLife2D.Screens
{
    public class LoginScreen : Screen
    {
        private Game1 _game;
        private Manager _manager;
        private TextBox _login;
        private TextBox _password;
        private Button _loginBtn;
        private Button _exitBtn;
        private Label _messageLbl;
        private Window _window;
        private Texture2D _errorImg;
        private Texture2D _waitImg;
        private Texture2D _questionImg;
        private AnimatedImageBox _imageBox;

        //Окно выбора персонажа
        private Window _characterSelectionWindow;
        private ListBox _charsLb;
        private Button _charSelect;
        private Button _newChar;
        private Button _delChar;
        private Label _infoLabel;
        //----------------------------------------------
        //Окно вопроса
        Window _questionMsg;
        public LoginScreen(Game1 game)
        {
            _game = game;
            _manager = new Manager(game, game.Graphics, "Default");
            _manager.SkinDirectory = "Content\\Skins\\";
            _manager.AutoCreateRenderTarget = true;
            //_manager.RenderTarget = game.GraphicsDevice.GetRenderTargets()[0].RenderTarget;
            LoadContent(_game.Content);
        }
        public override void LoadContent(Microsoft.Xna.Framework.Content.ContentManager content)
        {
            _errorImg = content.Load<Texture2D>("Skins\\Default\\Images\\Icon.Error");
            _waitImg = content.Load<Texture2D>("Images\\GUI\\wait");
            _questionImg = content.Load<Texture2D>("Skins\\Default\\Images\\Icon.Question");

            _manager.Initialize();

            _window = new Window(_manager);
            _window.Init();
            _window.Text = "LogIn window";
            _window.Width = 400;
            _window.Height = 400;
            _window.Center();
            _window.Movable = false;
            _window.Resizable = false;
            _window.CloseButtonVisible = false;
            //_window.CloseButtonVisible = true;
            _window.Visible = true;

            _login = new TextBox(_manager);
            _login.Init();
            _login.ColorMode = true;
            _login.Parent = _window;
            _login.Height = 20;
            _login.Width = 350;
            _login.SetPosition(25, 25);
            _login.Text = "Логин";
            //_login.CanSelect = false;
            //_login.CaretVisible = true;

            _password = new TextBox(_manager);
            _password.Init();
            _password.Parent = _window;
            _password.Height = 20;
            _password.Width = 350;
            _password.SetPosition(25, 50);
            _password.Text = "Пароль";
            _password.PasswordChar = '*';
            _password.Mode = TextBoxMode.Password;
            _password.KeyPress += new KeyEventHandler(_password_KeyPress);

            _loginBtn = new Button(_manager);
            _loginBtn.Init();
            _loginBtn.Parent = _window;
            _loginBtn.Height = 20;
            _loginBtn.Width = 170;
            _loginBtn.SetPosition(25, 75);
            _loginBtn.Text = "Войти";
            _loginBtn.Click += new TomShane.Neoforce.Controls.EventHandler(_loginBtn_Click);

            _exitBtn = new Button(_manager);
            _exitBtn.Init();
            _exitBtn.Parent = _window;
            _exitBtn.Height = 20;
            _exitBtn.Width = 170;
            _exitBtn.SetPosition(205, 75);
            _exitBtn.Text = "Выйти";
            _exitBtn.Click += new TomShane.Neoforce.Controls.EventHandler(_exitBtn_Click);

            _messageLbl = new Label(_manager);
            _messageLbl.Init();
            _messageLbl.Parent = _window;
            _messageLbl.Height = 20;
            _messageLbl.Width = 150;
            _messageLbl.SetPosition(25, 100);
            _messageLbl.Visible = false;
            _messageLbl.Color = Color.Red;

            _imageBox = new AnimatedImageBox(new Vector2(256, 256), _waitImg, _manager);
            _imageBox.Init();
            _imageBox.Parent = _window;
            _imageBox.Image = _waitImg;
            _imageBox.Frames = 32;
            _imageBox.Width = 128;
            _imageBox.Height = 128;
            _imageBox.SetPosition(134, 120);
            _imageBox.Visible = false;

            _manager.Add(_window);

            base.LoadContent(content);
        }

        public void Login()
        {
            _imageBox.Visible = true;
            new Thread(() =>
            {
                _game.ConnectToServer(_login.Text, _password.Text);
            }).Start();
        }
        public void LoginResult(AccountInfo accountInfo, string errorMessage)
        {
            _imageBox.Visible = false;
            if (errorMessage != null)
            {
                ShowMessageError(errorMessage, "Ошибка");
                return;
            }
            _window.Visible = false;

            _characterSelectionWindow = new Window(_manager);

            _characterSelectionWindow.Init();
            _characterSelectionWindow.Text = "Выбор персонажа";
            _characterSelectionWindow.Width = 400;
            _characterSelectionWindow.Height = 400;
            _characterSelectionWindow.Center();
            _characterSelectionWindow.Movable = false;
            _characterSelectionWindow.Resizable = false;
            _characterSelectionWindow.CloseButtonVisible = false;

            _charsLb = new ListBox(_manager);
            _charsLb.Init();
            _charsLb.Parent = _characterSelectionWindow;
            _charsLb.SetSize(350, 300);
            _charsLb.SetPosition(10, 10);
            _charsLb.ClientHeight = 300;
            _charsLb.ClientWidth = 350;

            foreach (SlotInfo si in accountInfo.Slots)
            {
                ListBoxItem lbi = new ListBoxItem(string.Format("{0}, Race:{1}, Money:{2}, PlayTime:{3}", si.Name, si.Race, si.Money, si.PlayTime), si);
                _charsLb.Items.Add(lbi);
            }

            _charSelect = new Button(_manager);
            _charSelect.Init();
            _charSelect.Parent = _characterSelectionWindow;
            _charSelect.SetPosition(10, 320);
            _charSelect.Text = "Выбрать";
            _charSelect.Click += new TomShane.Neoforce.Controls.EventHandler(_charSelect_Click);

            _newChar = new Button(_manager);
            _newChar.Init();
            _newChar.Parent = _characterSelectionWindow;
            _newChar.SetPosition(100, 320);
            _newChar.Text = "Создать";
            _newChar.Click += new TomShane.Neoforce.Controls.EventHandler(_newChar_Click);

            _delChar = new Button(_manager);
            _delChar.Init();
            _delChar.Parent = _characterSelectionWindow;
            _delChar.SetPosition(200, 320);
            _delChar.Text = "Удалить";
            _delChar.Click += new TomShane.Neoforce.Controls.EventHandler(_delChar_Click);

            _infoLabel = new Label(_manager);
            _infoLabel.Init();
            _infoLabel.Parent = _characterSelectionWindow;
            _infoLabel.SetPosition(10, 340);
            _infoLabel.SetSize(350, 20);
            _infoLabel.Text = string.Format("Поинты:{0}; Всего в игре:{1}", accountInfo.Points,
                                            accountInfo.TotalPlayTime);

            _manager.Add(_characterSelectionWindow);
        }

        public void SuccessOnDeleting(string name)
        {
            //ShowMessage(charId.ToString(), "");
            _charsLb.Items.Remove(_charsLb.Items.First(lbi => lbi.ToString().Split(',')[0] == name));//я бы сделал либо StartWith либо Contains)
        }

        void DeleteChar()
        {
            NetOutgoingMessage om = Game1.Client.CreateMessage();
            om.Write((short)PacketType.DelChar);
            SlotInfo si = (_charsLb.Items[_charsLb.ItemIndex] as ListBoxItem).Tag as SlotInfo;
            om.Write(si.Id);
            Game1.Client.SendMessage(om, NetDeliveryMethod.ReliableSequenced, 0);
        }

        void _delChar_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            if (_charsLb.ItemIndex != -1)
                ShowMessageQuestion("Вы действительно хотите удалить персонажа?!", "");
            //throw new NotImplementedException();
        }

        void _newChar_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            throw new NotImplementedException();
        }

        void _charSelect_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            if (_charsLb.ItemIndex != -1)
            {
                NetOutgoingMessage om = Game1.Client.CreateMessage();
                om.Write((short)PacketType.CharSelect);
                SlotInfo si = (_charsLb.Items[_charsLb.ItemIndex] as ListBoxItem).Tag as SlotInfo;
                om.Write(si.Id);
                Game1.Client.SendMessage(om, NetDeliveryMethod.ReliableSequenced, 0);
            }
        }
        void _password_KeyPress(object sender, KeyEventArgs e)
        {
            if (e.Key == Keys.Enter)
            {
                Login();
            }
        }

        void _exitBtn_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            _game.Exit();
        }

        void _loginBtn_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            Login();
        }
        public void ShowMessageError(string message, string title)
        {
            Window msg = new Window(_manager);
            Button btn = new Button(_manager);
            TextBox tb = new TextBox(_manager);
            ImageBox img = new ImageBox(_manager);
            msg.Init();
            btn.Init();
            tb.Init();
            img.Init();

            msg.Width = 400;
            msg.Height = 200;
            msg.Text = title;
            msg.Resizable = false;
            msg.CloseButtonVisible = false;
            msg.Movable = false;
            msg.StayOnTop = true;
            msg.Center();
            //msg.Top = int.MaxValue;

            img.Image = _errorImg;
            img.Parent = msg;
            img.SetPosition(10, 10);

            tb.SetPosition(70, 10);
            tb.Width = 300;
            tb.Height = 120;
            //tb.Mode = TextBoxMode.Multiline;
            tb.Text = message;
            tb.Parent = msg;
            tb.DrawBorders = false;
            tb.ReadOnly = true;
            tb.CanFocus = false;
            tb.TextColor = Color.Red;
            //tb.Init();

            btn.SetPosition(150, 130);
            btn.Text = "OK";
            btn.Height = 20;
            btn.Width = 100;
            btn.Parent = msg;
            btn.Click += new TomShane.Neoforce.Controls.EventHandler(btn_Click);


            _manager.Add(msg);
        }

        public void ShowMessageQuestion(string message, string title)
        {
            if(_questionMsg!= null)
            {
                return;
            }
            _questionMsg = new Window(_manager);
            Button btnYes = new Button(_manager);
            Button btnNo = new Button(_manager);
            TextBox tb = new TextBox(_manager);
            ImageBox img = new ImageBox(_manager);
            _questionMsg.Init();
            btnYes.Init();
            btnNo.Init();
            tb.Init();
            img.Init();

            _questionMsg.Width = 400;
            _questionMsg.Height = 200;
            _questionMsg.Text = title;
            _questionMsg.Resizable = false;
            _questionMsg.CloseButtonVisible = false;
            _questionMsg.Movable = false;
            _questionMsg.StayOnTop = true;
            _questionMsg.Center();
            //msg.Top = int.MaxValue;

            img.Image = _questionImg;
            img.Parent = _questionMsg;
            img.SetPosition(10, 10);

            tb.SetPosition(70, 10);
            tb.Width = 300;
            tb.Height = 120;
            //tb.Mode = TextBoxMode.Multiline;
            tb.Text = message;
            tb.Parent = _questionMsg;
            tb.DrawBorders = false;
            tb.ReadOnly = true;
            tb.CanFocus = false;
            tb.TextColor = Color.Red;
            //tb.Init();

            btnYes.SetPosition(96, 130);
            btnYes.Text = "Да";
            btnYes.Height = 20;
            btnYes.Width = 100;
            btnYes.Parent = _questionMsg;
            btnYes.Click += new TomShane.Neoforce.Controls.EventHandler(btnYes_Click);

            btnNo.SetPosition(204, 130);
            btnNo.Text = "Нет";
            btnNo.Height = 20;
            btnNo.Width = 100;
            btnNo.Parent = _questionMsg;
            btnNo.Click += new TomShane.Neoforce.Controls.EventHandler(btn_Click);

            _manager.Add(_questionMsg);
        }

        void btnYes_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            DeleteChar();
            Button btn = (Button)sender;
            Window wnd = (Window)((ClipBox)btn.Parent).Parent;
            wnd.Close();
        }

        void btn_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            Button btn = (Button)sender;
            Window wnd = (Window)((ClipBox)btn.Parent).Parent;
            wnd.Close();
            //throw new NotImplementedException();
        }
        public override void Draw(GameTime gameTime)
        {
            if (Initialized)
            {
                _manager.BeginDraw(gameTime);
                _game.GraphicsDevice.Clear(Color.Black);

                _manager.EndDraw();
                base.Draw(gameTime);
            }
        }
        public override void Update(GameTime gameTime)
        {
            if (Initialized)
            {
                _manager.Update(gameTime);
                _imageBox.UpdateImg(gameTime);
                base.Update(gameTime);
            }
        }
        public override void Dispose()
        {
            _messageLbl.Dispose();
            _messageLbl = null;
            _password.Dispose();
            _password = null;
            _loginBtn.Dispose();
            _loginBtn = null;
            _login.Dispose();
            _login = null;
            _exitBtn.Dispose();
            _exitBtn = null;
            _errorImg.Dispose();
            _errorImg = null;
            _window.Dispose();
            _window = null;
            _manager.Dispose();
            _manager = null;
            _game = null;
            base.Dispose();
        }
    }
}
